package com.wrupple.muba.catalogs.client.module.services.logic.impl;

import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONValue;
import com.google.inject.Inject;
import com.wrupple.muba.catalogs.client.module.services.logic.CatalogDescriptionService;
import com.wrupple.vegetate.client.module.services.logic.EntryProcessingService;
import com.wrupple.vegetate.domain.CatalogDescriptor;

public class EntryProcessingServiceImpl implements EntryProcessingService{
	
	private CatalogDescriptionService descriptionService;
	
	static EntryProcessingServiceImpl instance;

	@Inject
	public EntryProcessingServiceImpl(CatalogDescriptionService descriptionService) {
		super();
		this.descriptionService = descriptionService;
		instance = this;
	}
	
	@Override
	public JSONValue getEntryField(String fieldName, JSONObject entry, CatalogDescriptor catalog) {
		return entry.get(fieldName);
	}

	@Override
	public String getEntryId(JavaScriptObject entry, CatalogDescriptor catalog) {
		String key = catalog.getKeyField();
		return getFieldValueAsString(entry,key);
	}
	
	@Override
	public String getEntryId(JavaScriptObject entry, String catalog) {
		return getEntryId(entry, descriptionService.loadFromCache(catalog));
	}
	
	@Override
	public String getEntryName(JavaScriptObject entry, String catalog) {
		CatalogDescriptor c = descriptionService.loadFromCache(catalog);
		String key = c.getDescriptiveField();
		if(key==null){
			return getEntryId(entry, catalog);
		}
		return getFieldValueAsString(entry,key);
	}
	
	
	public static String name(JavaScriptObject entry, String catalog){
		return instance.getEntryName(entry, catalog);
	}
	
	
	public static String id(JavaScriptObject entry, String catalog){
		return instance.getEntryId(entry, catalog);
	}
	

	private native final String getFieldValueAsString(JavaScriptObject entry, String field) /*-{
		return entry[field]+"";
	}-*/;
	private static native final String setFieldValueAsString(JavaScriptObject entry, String field,String value) /*-{
		entry[field]=value;
	}-*/;

}
